package com.alferd.mall.mq.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * Rabbitmq配置类
 */
@Configuration
public class RabbitmqConfig {

    @Autowired
    private Environment env;

    @Autowired
    private CachingConnectionFactory connectionFactory;

    /**
     * 单一消费者
     * @return
     */
    @Bean(name = "singleListenerContainer")
    public SimpleRabbitListenerContainerFactory listenerContainer(){
        SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        factory.setConcurrentConsumers(1);
        factory.setMaxConcurrentConsumers(1);
        factory.setPrefetchCount(1);
        factory.setTxSize(1);
        factory.setAcknowledgeMode(AcknowledgeMode.AUTO);
        return factory;
    }


    /**
     * 创建queue
     * @return
     */
    @Bean
    public Queue miaoshaQueue() {
        return new Queue(env.getProperty("user.miaosha.queue.name"),//Queue名字
                true,//是否持久化
                false,//是否排他
                false);//是否自动删除
    }

    /**
     * 创建exchange
     * @return
     */
    @Bean
    public TopicExchange miaoshaExchange() {
        return new TopicExchange(env.getProperty("user.miaosha.exchange.name"),
                true,//是否持久化
                false);//exclusive：是否排他
    }

    /**
     * 绑定
     * @return
     */
    @Bean
    public Binding miaoshaBinding() {
        return BindingBuilder.bind(miaoshaQueue()).to(miaoshaExchange()).with(env.getProperty("user.miaosha.routing.key.name"));
    }
}
